package com.example.module.linker;

import java.io.File;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
import twitter4j.media.MediaProvider;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.example.entity.Const;
import com.example.module.widget.CustomWebDialog;
import com.example.persistence.ImageActivity;
import com.example.persistence.MyApplication;

public class TwitterLink {
	private static final String REDIRECT_URI = "twconnect://success";
	
	private Twitter twitter;
	private RequestToken requestToken;
	
	private MyApplication application;
	private ImageActivity activity;
	private CustomWebDialog dialog;

	private AsyncTask<PostJob, Integer, String> postTask;

	private ProgressDialog progressDialog;

	private interface AuthorizeListener {
		public void doPublish();
	}
	
	public TwitterLink(ImageActivity activity) {
		this.activity = activity;
		this.application = activity.application;
		
		ConfigurationBuilder builder = new ConfigurationBuilder();
		builder.setOAuthConsumerKey(Const.TWITTER_CONSUIMER_KEY);
		builder.setOAuthConsumerSecret(Const.TWITTER_CONSUMER_SECRET);
		if (application.getTwitterAccessToken() != null) {
			builder.setOAuthAccessToken(application.getTwitterAccessToken().getToken());
			builder.setOAuthAccessTokenSecret(application.getTwitterAccessToken().getTokenSecret());	
		}
		Configuration configuration = builder.build();
		this.twitter = new TwitterFactory(configuration).getInstance();
		
		progressDialog = new ProgressDialog(activity);
		progressDialog.setMessage("전송 중... ");
		progressDialog.setCancelable(false);
	}
	
	private void authorize(final AuthorizeListener authorizeListener) {
		dialog = new CustomWebDialog(activity);
		dialog.redirectUrl = REDIRECT_URI;
		dialog.setOnCompleteListener(new CustomWebDialog.OnCompleteListener() {
			@Override
			public void onComplete(final String oauth_verifier) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
							Log.e("TwitterLink authorize", "accessToken=" + accessToken.getToken());
							Log.e("TwitterLink authorize", "accessTokenSecret=" + accessToken.getTokenSecret());
							application.setTwitterAccessToken(accessToken);
							if (authorizeListener != null)
								authorizeListener.doPublish();
							
						} catch (TwitterException e) {
							e.printStackTrace();
						}			
					}
				}).start();
			}
		});

		new AsyncTask<Void, Integer, String>() {
			
			@Override
			protected String doInBackground(Void... params) {
				String url = null;
				try {
					requestToken = twitter.getOAuthRequestToken(REDIRECT_URI);
					url = requestToken.getAuthorizationURL() + "&lang=ko";
					Log.e("TwitterLink authorize", "AuthorizationURL=" + url);
				} catch (TwitterException e) {
					e.printStackTrace();
				}	
				
				return url;
			}
			
			@Override
			protected void onPostExecute(String url) {
				Log.e("onPostExecute", "result="  +url);
				super.onPostExecute(url);
				dialog.show();
				dialog.loadUrl(url);
			}
		}.execute();
	}
	

	public void publish(String message){
		Log.e("TwitterLink publish", "twitter.getAuthorization().isEnabled()=" + twitter.getAuthorization().isEnabled());
		PostJob postJob = new PostJob(message);
		publishJob(postJob);
	}
	
	public void publish(String message, File image){
		Log.e("TwitterLink publish", "twitter.getAuthorization().isEnabled()=" + twitter.getAuthorization().isEnabled());
		PostJob postJob = new PostJob(message, image);
		publishJob(postJob);
	}
	
	private void publishJob(final PostJob postJob) {
		postTask = new AsyncTask<PostJob, Integer, String>(){
			@Override
			protected void onPreExecute() {
				progressDialog.show();
				super.onPreExecute();
			}
			
			@Override
			protected String doInBackground(PostJob... posts) {
				Log.e("doInBackground", "posts.length=" + posts.length);
				
				String result = null;
				for (PostJob post : posts) {
					Log.e("doInBackground", "post=" + post);
					if (post == null)
						continue;
					
					if (post.getImage() != null && post.getImage().isFile())
						result = publishPhoto(post.getMessage(), post.getImage());
					else
						result = publishStatus(post.getMessage());
				}
				
				return result;
			}

			@Override
			protected void onPostExecute(String result) {
				progressDialog.dismiss();
				Log.e("onPostExecute", "result=" + result);
				if (result != null && result.length() > 0)
					Toast.makeText(activity, "트위터 포스팅 성공", Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(activity, "트위터 포스팅 실패", Toast.LENGTH_SHORT).show();
			};
		};
		
		if (!twitter.getAuthorization().isEnabled()) {
			authorize(new AuthorizeListener() {
				@Override
				public void doPublish() {
					postTask.execute(postJob);
				}
			});
		}
		else {
			postTask.execute(postJob);
		}
	}
	
	private String publishStatus(String message) {
		Log.e("TwitterLink publishStatus", "message=" + message);
		
		String result = null;
		try {
			Status status = twitter.updateStatus(message);
			result = String.valueOf(status.getId());
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	private String publishPhoto(String message, File image) {
		Log.e("TwitterLink publishPhoto", "message=" + message + " image=" + image.isFile());

		String result = null;
		try {
			ImageUpload upload = new ImageUploadFactory(twitter.getConfiguration()).getInstance(MediaProvider.TWITTER);
			result = upload.upload(image, message);
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
